<script setup lang="ts">
import { computed, ref } from 'vue'
// ts类型
import type {
  SpuData,
  AllTrademark,
  SpuHasImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData,
  Trademark,
  SpuImg,
  SaleAttr,
  HasSaleAttr,
  SaleAttrVale,
} from '@/api/product/spu/type'
// 接口
import {
  reqAllSaleAttr,
  reqHasTrademark,
  reqSpuHasSaleAttr,
  reqImageList,
  reqAddOrUpdateSpu,
} from '@/api/product/spu'
import { ElMessage } from 'element-plus'

let emit: any = defineEmits(['changeScene'])
//存储已有的SPU这些数据
let AllTradeMark = ref<Trademark[]>([])
//商品图片
let ImgList = ref<SpuImg[]>([])
//已有的SPU销售属性
let SaleAttrList = ref<SaleAttr[]>([])
//全部销售属性
let HasSaleAttrList = ref<HasSaleAttr[]>([])
// 存储已有的spu对象
let SpuParams = ref<SpuData>({
  category3Id: '', //收集三级分类的ID
  spuName: '', //SPU的名字
  description: '', //SPU的描述
  tmId: '', //品牌的ID
  spuImageList: [],
  spuSaleAttrList: [],
})

const cancel = () => {
  emit('changeScene', { flag: 0, params: 'update' })
}
// 子组件的方法
const initHasSpuData = async (spu: SpuData) => {
  //存储已有的SPU对象,将来在模板中展示
  SpuParams.value = spu
  //spu:即为父组件传递过来的已有的SPU对象[不完整]
  // 获取全部品牌的数据
  const result: AllTrademark = await reqHasTrademark()
  // 获取某一个品牌旗下的全部售卖商品的图片
  const result1: SpuHasImg = await reqImageList(spu.id as number)
  // 获取已有的spu销售属性的数据
  const result2: SaleAttrResponseData = await reqSpuHasSaleAttr(
    spu.id as number,
  )
  // 获取整个项目全部spu的销售属性
  const result3: HasSaleAttrResponseData = await reqAllSaleAttr()

  AllTradeMark.value = result.data
  ImgList.value = result1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  SaleAttrList.value = result2.data
  HasSaleAttrList.value = result3.data
}

let dialogVisible = ref<boolean>(false)
let dialogImageUrl = ref<string>('')

const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = () => {}
const handlerUpload = (file: any) => {
  if (
    file.type === 'image/png' ||
    file.type === 'image/jpeg' ||
    file.type === 'image/gif'
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于3M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}

let saleAttrIdAndValueName = ref<string>('')

let unSelectSaleAttr = computed(() => {
  let unSelectAttr = HasSaleAttrList.value.filter((item) => {
    return SaleAttrList.value.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectAttr
})

const addSaleAttr = () => {
  // baseSaleAttrId: number
  // saleAttrName: string
  // spuSaleAttrValueList: spuSaleAttrValueList
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')

  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }

  SaleAttrList.value.push(newSaleAttr)
  saleAttrIdAndValueName.value = ''
}
const toLook = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row
  let newSaleAttrVale: SaleAttrVale = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }
  if (saleAttrValue?.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值重复',
    })
    return
  }
  row.spuSaleAttrValueList.push(newSaleAttrVale)
  row.flag = false
}

const toEdit = (row: SaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}

const save = async () => {
  // 整理参数
  // 照片墙数据
  SpuParams.value.spuImageList = ImgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })

  SpuParams.value.spuSaleAttrList = SaleAttrList.value

  // 发送请求：
  let result: any = await reqAddOrUpdateSpu(SpuParams.value)

  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    })
    emit('changeScene', {
      flag: 0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    })
  }
}
// 添加回调
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  Object.assign(SpuParams.value, {
    category3Id: '', //收集三级分类的ID
    spuName: '', //SPU的名字
    description: '', //SPU的描述
    tmId: '', //品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
  })
  //清空照片
  ImgList.value = []
  //清空销售属性
  SaleAttrList.value = []
  saleAttrIdAndValueName.value = ''
  SpuParams.value.category3Id = c3Id
  //spu:即为父组件传递过来的已有的SPU对象[不完整]
  // 获取全部品牌的数据
  const result: AllTrademark = await reqHasTrademark()
  // 获取整个项目全部spu的销售属性
  const result3: HasSaleAttrResponseData = await reqAllSaleAttr()

  AllTradeMark.value = result.data

  HasSaleAttrList.value = result3.data
}

// 对外暴露
defineExpose({ initHasSpuData, initAddSpu })
</script>
<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        v-model="SpuParams.spuName"
        placeholder="请输入SPU名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId" placeholder="请选择">
        <el-option
          v-for="item in AllTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        v-model="SpuParams.description"
        type="textarea"
        placeholder="请输入SPU名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <!-- v-model:fileList->展示默认图片
          list-type:文件列表的类型
          action:上传图片的接口地址
       -->
      <el-upload
        v-model:file-list="ImgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handlerUpload"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img
          style="width: 100%; height: 100%"
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
        />
      </el-dialog>
    </el-form-item>

    <el-form-item label="SPU销售属性">
      <el-select
        style="width: 150px"
        :placeholder="
          unSelectSaleAttr.length
            ? `还未选择${unSelectSaleAttr.length}个`
            : '无'
        "
        v-model="saleAttrIdAndValueName"
      >
        <el-option
          :label="item.name"
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        style="margin-left: 20px"
        type="primary"
        icon="Plus"
        size="default"
        :disabled="saleAttrIdAndValueName ? false : true"
        @click="addSaleAttr"
      >
        添加属性值
      </el-button>

      <el-table :data="SaleAttrList" border style="margin-top: 20px">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="saleAttrName"
          label="销售属性名称"
          width="120px"
        ></el-table-column>
        <el-table-column prop="" label="销售属性值">
          <template #="{ row }">
            <el-tag
              style="margin: 0 5px"
              v-for="(tag, index) in row.spuSaleAttrValueList"
              :key="tag.id"
              closable
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.flag === true"
              @blur="toLook(row)"
              v-model="row.saleAttrValue"
              placeholder="请输入属性值"
              size="small"
              style="width: 100px"
            ></el-input>
            <el-button
              v-else
              @click="toEdit(row)"
              type="primary"
              size="small"
              icon="plus"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ $index }">
            <el-button
              @click="SaleAttrList.splice($index, 1)"
              type="danger"
              size="small"
              icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button
        type="primary"
        :disabled="SaleAttrList.length > 0 ? false : true"
        size="default"
        @click="save"
      >
        保存
      </el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<style scoped lang="scss"></style>
